<template>
    <div class="template-detail" v-loading="loading">
        <el-card v-if="template" class="detail-card">
            <!-- 标题和描述 -->
            <div class="header">
                <h1>{{ template.name }}</h1>
                <p class="description">{{ template.description }}</p>
                <div class="meta">
                    <el-tag>{{ template.category }}</el-tag>
                    <el-tag v-for="tag in template.tags" :key="tag" effect="plain">{{ tag }}</el-tag>
                </div>
            </div>

            <!-- 预览图片 -->
            <div class="preview">
                <el-carousel :interval="4000" type="card" height="400px">
                    <el-carousel-item v-for="image in template.previewImages" :key="image">
                        <el-image :src="image" fit="contain" :preview-src-list="template.previewImages" />
                    </el-carousel-item>
                </el-carousel>
            </div>

            <!-- 参数配置 -->
            <div class="params-config">
                <h2>参数配置</h2>
                <el-form :model="params" label-width="120px">
                    <template v-for="(value, key) in template.defaultParams" :key="key">
                        <el-form-item :label="formatParamLabel(key)">
                            <!-- 根据参数类型显示不同的输入控件 -->
                            <template v-if="typeof value === 'number'">
                                <el-input-number v-model="params[key]" :step="0.1" />
                            </template>
                            <template v-else-if="typeof value === 'string'">
                                <el-input v-model="params[key]" type="textarea" :rows="2" />
                            </template>
                            <template v-else>
                                <el-input v-model="params[key]" />
                            </template>
                        </el-form-item>
                    </template>
                </el-form>
            </div>

            <!-- 生成按钮 -->
            <div class="actions">
                <el-button type="primary" size="large" :loading="generating" @click="handleGenerate">
                    开始生成
                </el-button>
            </div>

            <!-- 元数据信息 -->
            <div class="metadata">
                <el-descriptions :column="3" border>
                    <el-descriptions-item label="模型版本">
                        {{ template.metadata?.modelVersion }}
                    </el-descriptions-item>
                    <el-descriptions-item label="难度">
                        {{ template.metadata?.difficulty }}
                    </el-descriptions-item>
                    <el-descriptions-item label="预计用时">
                        {{ template.metadata?.estimatedTime }}秒
                    </el-descriptions-item>
                </el-descriptions>
            </div>
        </el-card>

        <!-- 生成结果对话框 -->
        <el-dialog v-model="showResult" title="生成结果" width="80%" :close-on-click-modal="false">
            <div class="result-content">
                <el-image v-if="resultImage" :src="resultImage" fit="contain" />
                <div v-else class="generating-status">
                    <el-progress type="circle" :percentage="progress" />
                    <p>{{ statusMessage }}</p>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showResult = false">关闭</el-button>
                    <el-button type="primary" @click="handleSave" :disabled="!resultImage">
                        保存
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { WorkflowTemplate } from '@/types';
import { getTemplate } from '@/api/template';
import { generateImage, saveGenerationResult } from '@/api/generation';

const route = useRoute();
const template = ref<WorkflowTemplate | null>(null);
const params = ref<Record<string, any>>({});
const loading = ref(false);
const generating = ref(false);
const showResult = ref(false);
const resultImage = ref('');
const progress = ref(0);
const statusMessage = ref('');

// 加载模板数据
async function loadTemplate() {
    loading.value = true;
    try {
        const id = route.params.id as string;
        const data = await getTemplate(id);
        template.value = data;
        params.value = { ...data.defaultParams };
    } catch (error) {
        ElMessage.error('加载模板失败');
    } finally {
        loading.value = false;
    }
}

// 格式化参数标签
function formatParamLabel(key: string) {
    return key.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
}

// 处理生成
async function handleGenerate() {
    generating.value = true;
    showResult.value = true;
    progress.value = 0;
    resultImage.value = '';
    statusMessage.value = '正在准备生成...';

    try {
        const result = await generateImage(template.value!._id, params.value);
        resultImage.value = result.imageUrl;
        statusMessage.value = '生成完成';
    } catch (error) {
        ElMessage.error('生成失败');
    } finally {
        generating.value = false;
    }
}

// 保存生成结果
async function handleSave() {
    try {
        await saveGenerationResult(
            resultImage.value,
            template.value!._id,
            params.value
        );
        ElMessage.success('保存成功');
        showResult.value = false;
    } catch (error) {
        ElMessage.error('保存失败');
    }
}

onMounted(() => {
    loadTemplate();
});
</script>

<style scoped>
.template-detail {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.header {
    margin-bottom: 24px;
}

.header h1 {
    margin: 0 0 16px;
}

.description {
    color: #666;
    margin-bottom: 16px;
}

.meta {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.preview {
    margin: 24px 0;
}

.params-config {
    margin: 24px 0;
}

.actions {
    margin: 24px 0;
    text-align: center;
}

.metadata {
    margin-top: 24px;
}

.result-content {
    min-height: 400px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.generating-status {
    text-align: center;
}

.generating-status p {
    margin-top: 16px;
    color: #666;
}
</style> 